/* eslint-disable react-hooks/exhaustive-deps */
import { Empty, Spin, Tag, Tree, Upload, UploadFile } from 'antd';
import { CodeContainerType } from '../../core/types';
import { UploadChangeParam } from 'antd/es/upload';
import { TreeDataNode } from '../CodeContainer';
import './index.scss'
import { debounce } from '../../common/Utils';

interface IProps {
    type: CodeContainerType
    loading: boolean,
    treeData?: TreeDataNode[]
    onExport: () => void
    onFilePathSelect: (path: string) => void
    onFolderChange: (data: UploadFile[]) => void
}

const FolderSide = (props: IProps) => {
    const { type, loading, onFilePathSelect, onFolderChange, treeData, onExport } = props;

    const handleFileChange = debounce((info: UploadChangeParam<UploadFile>): void => {
        if (info.fileList.length > 0) {
            const files = info.fileList;
            onFolderChange(files)
        }
    }, 1000);

    return <div className="folder-side flex-center">
        <div className="folder-content">
            <Tag className='title-tag' color={type === CodeContainerType.FROM ? '#fe7d3c' : '#108ee9'}>{type}</Tag>
            {treeData && treeData.length > 0 ? (
                <>
                    <Tree.DirectoryTree
                        className='folder-tree'
                        blockNode
                        showIcon
                        treeData={treeData}
                        onSelect={(_key, info) => {
                            if (info.node.isLeaf) {
                                onFilePathSelect(info.node.key.replace(/^[^/]*\//, ""))
                            }
                        }}
                    />
                </>
            ) :
                loading ?
                    <Spin style={{ marginTop: '40%', transform: 'translateY(-50%)' }} size='small' tip={'Translating'} spinning={loading} >{''}</Spin>
                    : <Empty style={{ marginTop: '50%', transform: 'translateY(-50%)' }} description={'Empty'} />}
        </div>

        {type == CodeContainerType.FROM &&
            <Upload
                multiple
                directory
                fileList={[]}
                showUploadList={false}
                beforeUpload={() => false} // 阻止自动上传
                onChange={handleFileChange}
                disabled={loading}
            >
                <button disabled={loading} className='sider-btn'>Import</button>
            </Upload>}
        {type == CodeContainerType.TO &&
            <button className='sider-btn' onClick={onExport} >Export</button>
        }
    </div >
}

export default FolderSide;